package com.shelpe.services.sinbad.utils;

import java.util.Date;

import javax.persistence.AttributeConverter;

import org.apache.commons.lang.math.NumberUtils;


public abstract class EntityUtils {

	public static class Day2IntConverter implements AttributeConverter<Date, Integer> {

		@Override
		public Integer convertToDatabaseColumn(Date attribute) {
			return (int) (attribute.getTime() / 1000);
		}

		@Override
		public Date convertToEntityAttribute(Integer dbData) {
			if (dbData == null) {
				return null;
			}
			long ts = dbData.intValue();
			return new Date(ts * 1000);
		}

	}

	public static class Day2StringConverter implements AttributeConverter<Date, String> {

		@Override
		public String convertToDatabaseColumn(Date attribute) {
			return attribute != null ? ((attribute.getTime() / 1000) + "") : "";
		}

		@Override
		public Date convertToEntityAttribute(String dbData) {
			if (dbData == null) {
				return null;
			}
			long ts = NumberUtils.toLong(dbData);
			if (ts <= 0) {
				return null;
			}
			return new Date(ts * 1000);
		}

	}
}
